package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = MenuService.class, protocol = "dubbo")
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    private List<Menu> returnList = new ArrayList<>();

    @Override
    public List findMenuByUser(String username) {
        //根据姓名查出用户id
        //根据用户id查出对应的角色
        //根据角色查出对应的菜单项
        //查询出所有级菜单
        //遍历所有菜单
        //查询所有菜单的id和父id,并把有父ID值的菜单封装到父对象中
        List<Menu> allMenuList = menuDao.findMenuByUsername(username);
        //创建父级菜单集合
        List<Menu> leaveList = new ArrayList<>();
        Menu workMenu = new Menu();
        workMenu.setName("工作台");
        workMenu.setPath("1");
        workMenu.setIcon("fa-dashboard");
        leaveList.add(workMenu);
        for (Menu menu : allMenuList) {
            Integer id = menu.getId();
            Integer parentMenuId = menu.getParentMenuId();
            if (parentMenuId==null){
                //将所有的父级菜单加到父级菜单集合中
                leaveList.add(menu);
                //通过父级菜单id查询子级菜单
            }else{
                //父级菜单id不为null时,遍历父级菜单集合
                for (Menu menu1 : leaveList) {
                    //拿到父级菜单的id
                    Integer id1 = menu1.getId();
                    if (id1==(parentMenuId)){
                        //将子级菜单封装到对应父级菜单中
                        List<Menu> children = menu1.getChildren();
                        children.add(menu);
                        menu1.setChildren(children);
                    }
                }

            }
        }
        return leaveList;
    }


    public void add(Menu menu)
    {
        menuDao.add(menu);
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckItem> page = menuDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void delete(Integer id)throws RuntimeException {
        //查询当前检查项是否和检查组关联
        long count =  menuDao.findCountByCheckItemId(id);
        if(count > 0){
            throw new RuntimeException("当前检查项被引用，不能删除");
        }
        menuDao.deleteById(id);
    }

    @Override
    public void edit(Menu menu) {
        menuDao.edit(menu);
    }

    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }
}
